package com.ziq.zcamp.post

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.route.DistanceResult
import com.amap.api.services.route.DistanceSearch
import com.blankj.utilcode.util.AppUtils
import com.ziq.base.base.BaseActivity
import com.ziq.base.extension.*
import com.ziq.base.utils.permission.PermissionUtil
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.place.LocationInfo
import com.ziq.zcamp.databinding.ActivityMapBinding
import com.ziq.zcamp.main.BottomSheetDialog
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.util.MapUtil
import java.text.DecimalFormat


class MapActivity: BaseActivity() , AMap.OnInfoWindowClickListener, AMap.OnMarkerClickListener{

    companion object {
        const val MAP_LOCATION = "MAP_LOCATION"
        fun open(context: Context, location: LocationInfo){
            val intent = Intent(context, MapActivity::class.java)
            intent.putExtra(MAP_LOCATION, location)
            GlobalContextManager.startActivity(context, intent)
        }

        fun showMapNavigationList(context: Activity, name: String, latitude :String, longitude :String, source:String){

            val menuList = mutableListOf<String>()
            //百度地图、高德地图、腾讯地图、谷歌地图
            if(AppUtils.isAppInstalled(MapUtil.BAIDU_MAP)){
                val text = GlobalContextManager.getString(R.string.map_name_baidu)
                menuList.add(text)
            }
            if(AppUtils.isAppInstalled(MapUtil.GAODE_MAP)){
                val text = GlobalContextManager.getString(R.string.map_name_gaode)
                menuList.add(text)
            }
            if(AppUtils.isAppInstalled(MapUtil.TENCENT_MAP)){
                val text = GlobalContextManager.getString(R.string.map_name_tencent)
                menuList.add(text)
            }
            if(AppUtils.isAppInstalled(MapUtil.GOOGLE_MAP)){
                val text = GlobalContextManager.getString(R.string.map_name_google)
                menuList.add(text)
            }
            if(menuList.isEmpty()){
                val text = GlobalContextManager.getString(R.string.no_map)
                Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
                return
            }
            BottomSheetDialog.Builder(context)
                .setList(menuList, object : BottomSheetDialog.ActionCallBack {
                    override fun onActionClick(dialog: BottomSheetDialog, position: Int, text: String) {
                        dialog.dismiss()
                        when(text){
                            GlobalContextManager.getString(R.string.map_name_baidu) -> {
                                MapUtil.openBaiDuGuide(context, name, latitude, longitude)
                            }
                            GlobalContextManager.getString(R.string.map_name_gaode) -> {
                                MapUtil.openGaoDeGuide(context, name, latitude, longitude)
                            }
                            GlobalContextManager.getString(R.string.map_name_tencent) -> {
                                MapUtil.openTencentGuide(context, name, latitude, longitude)
                            }
                            GlobalContextManager.getString(R.string.map_name_google) -> {
                                MapUtil.openGoogleGuide(context, name, latitude, longitude)
                            }
                        }
                        dialog.dismiss()
                    }
                })
                .build()
                .show()
        }
    }

    private val binding: ActivityMapBinding by binding()
    private var location: LocationInfo? = null
    private var distance: Float? = null
    var aMap:AMap? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            if(intent.hasExtra(MAP_LOCATION)){
                val tempLocation  = intent.getSerializableExtra(MAP_LOCATION) as LocationInfo
                if(tempLocation.longitude?.isNotEmpty() == true && tempLocation.latitude?.isNotEmpty() == true){
                    location = tempLocation
                }
            }
        }catch (e:Exception){
            println("$e")
        }

        binding.root
        binding.back.click {
            finish()
        }

        binding.btnChangeMapType.click {
            if(aMap?.mapType == AMap.MAP_TYPE_SATELLITE){
                aMap?.mapType = AMap.MAP_TYPE_NORMAL
                binding.btnChangeMapType.setImageResource(R.drawable.icon_satellite_map)
                try {
                    val mapStyle = CustomMapStyleOptions()
                    val styleData = resources.assets.open("style.data")
                    val styleExtraData = resources.assets.open("style_extra.data")
                    mapStyle.setEnable(true)
                    mapStyle.setStyleData(styleData.readBytes())
                    mapStyle.setStyleExtraData(styleExtraData.readBytes())
                    aMap?.setCustomMapStyle(mapStyle)
                }catch (e: java.lang.Exception){
                }
            } else {
                aMap?.mapType = AMap.MAP_TYPE_SATELLITE
                binding.btnChangeMapType.setImageResource(R.drawable.icon_plane_map)
            }
        }

        binding.btnCurrentLocation.click {
            if(distanceEnd != null){
                moveCamera(LatLng(distanceEnd!!.latitude, distanceEnd!!.longitude))
            }
        }


        binding.map.onCreate(savedInstanceState)
        aMap = binding.map.map
        aMap?.setTrafficEnabled(true);// 显示实时交通状况
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap?.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
        aMap?.uiSettings?.isScaleControlsEnabled = true //比例尺
        aMap?.uiSettings?.isZoomControlsEnabled = false
        aMap?.maxZoomLevel = maxZoomLevel
        aMap?.isMyLocationEnabled = true // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        // 设置定位的类型为根据地图面向方向旋转
        aMap?.myLocationStyle = MyLocationStyle().interval(5000).myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER)
        //marker 点击事件
        aMap?.setOnMarkerClickListener(this)
        //marker 对应infowindow 点击事件
        aMap?.setOnInfoWindowClickListener(this)
        aMap?.setInfoWindowAdapter(object : AMap.InfoWindowAdapter {
            override fun getInfoContents(marker: Marker?): View? {
                return null
            }

            override fun getInfoWindow(marker: Marker?): View? {
                val view: View = LayoutInflater.from(this@MapActivity).inflate(R.layout.map_info_window, null)
                view.findViewById<TextView>(R.id.title).text = marker?.title
                view.findViewById<TextView>(R.id.distance).text = marker?.snippet
                return view
            }

        })
        if(location != null){
            //参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
            //地图的缩放级别一共分为17级，从3到19。数字越大，展示的图面信息越精细。
            var longitude = location!!.longitude!!.toDouble()
            var latitude  = location!!.latitude!!.toDouble()
            distanceEnd = LatLonPoint(latitude, longitude)

            val latLng = LatLng(latitude, longitude)
            moveCamera(latLng)

            marker = aMap?.addMarker(
                MarkerOptions().position(latLng).title(location!!.site)
                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.icon_camp_marker_sel)))
            )
            marker?.showInfoWindow()
            //定位
            binding.root.post {
                getLocation()
            }
        }

    }

    val mapLevel = 9f
    val maxZoomLevel = 18.8f  //最大放大等级

    fun moveCamera(latlng: LatLng?, level:Float = mapLevel){
        latlng?.let {
            val cameraUpdate = CameraUpdateFactory.newCameraPosition(CameraPosition(it, level, 0f ,0f))
            aMap?.animateCamera(cameraUpdate)
        }
    }

    var marker :Marker? = null
    @SuppressLint("CheckResult")
    fun getLocation(){
        PermissionUtil.requestLocationPermission(this, onGrant = {
            MapUtil.getCurrentLocation(callback = {
                distanceStart = LatLonPoint(it.latitude, it.longitude)
                calculateRouteDistanceAsyn()
            })
        }, onReject = {
        }, onRemind = {
        })
    }

    var distanceStart :LatLonPoint? = null
    var distanceEnd:LatLonPoint? = null
    fun calculateRouteDistanceAsyn(){
        if(distanceStart != null && distanceEnd != null){
            val distanceSearch = DistanceSearch(this)
            distanceSearch.setDistanceSearchListener(object : DistanceSearch.OnDistanceSearchListener {
                override fun onDistanceSearched(distanceResult: DistanceResult?, errorCode: Int) {
                    val distanceItem = distanceResult?.distanceResults?.get(0)
                    if(distanceItem != null){
                        val distance = distanceItem.distance
                        val mapDistance = GlobalContextManager.getString(R.string.map_distance)
                        if(distance > 1000){
                            marker?.snippet = "$mapDistance${DecimalFormat("0.##").format(distance / 1000)}km"
                        } else {
                            marker?.snippet = "$mapDistance${distance.toInt()}m"
                        }
                        marker?.showInfoWindow()
                    }
                }
            })

            val latLonPoints: MutableList<LatLonPoint> = ArrayList()
            latLonPoints.add(distanceStart!!)
            val distanceQuery = DistanceSearch.DistanceQuery()
            distanceQuery.setOrigins(latLonPoints)
            distanceQuery.setDestination(distanceEnd)
            //设置测量方式，支持直线和驾车
            distanceQuery.setType(DistanceSearch.TYPE_DISTANCE)
            distanceSearch.calculateRouteDistanceAsyn(distanceQuery)
        }
    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        binding.map.onSaveInstanceState(outState)
    }

    override fun onResume() {
        super.onResume()
        binding.map.onResume()
    }

    override fun onPause() {
        super.onPause()
        binding.map.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.map.map.removeOnInfoWindowClickListener(this)
        binding.map.map.removeOnMarkerClickListener(this)
        binding.map.onDestroy()
    }

    override fun onInfoWindowClick(marker: Marker) {
        showMapNavigationList(this@MapActivity, location?.site!!, location?.latitude!!, location?.longitude!!, "camp_map_detail")
    }

    override fun onMarkerClick(marker: Marker?): Boolean {
        return false
    }

}